package com.rr.middle;

import com.rr.entity.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuangcanrun
 * @Date 2024/06/12/18:33
 * @description
 **/

/*
* https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
* 给出中序和后序遍历结果，构建出树
* */
public class BuildTree2 {

    private Map<Integer, Integer> valIndexMap = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < inorder.length; i++) {
            valIndexMap.put(inorder[i], i);
        }

        return doBuildTree(0, inorder.length - 1, 0, postorder.length - 1, inorder, postorder);
    }

    private TreeNode doBuildTree(int inLeft, int inRight, int postLeft, int postRight, int[] inorder, int[] postorder) {
        if (inLeft == inRight) {
            return new TreeNode(inorder[inLeft]);
        } else if (inLeft > inRight) {
            return null;
        }
        int rootValue = postorder[postRight];
        TreeNode root = new TreeNode(rootValue);
        int rootIndex = valIndexMap.get(rootValue);
        int leftNum = rootIndex - inLeft;
        root.left = doBuildTree(inLeft, inLeft + leftNum-1, postLeft, postLeft + leftNum - 1, inorder, postorder);
        root.right = doBuildTree(rootIndex + 1, inRight, postLeft + leftNum, postRight - 1, inorder, postorder);
        return root;
    }

    public static void main(String[] args) {
        BuildTree2 buildTree = new BuildTree2();
        TreeNode tree = buildTree.buildTree(new int[] {1,2,3,4}, new int[] {3,2,4,1});
//        TreeNode tree = buildTree.buildTree(new int[] {3,2,1}, new int[] {3,2,1});
        System.out.println(tree);
    }
}
